package library.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;

import library.logger.Logger;

/**
 * Created by Mr.Fan on 2016-5-3.
 */
public class Shell {

    public static boolean cmd(String... command) {
        return cmd(false, command);
    }

    public static boolean cmd(boolean su, String... command) {
        Process mProcess = null;
        DataInputStream is = null;
        DataInputStream es = null;
        DataOutputStream os = null;
        StringBuilder sb = new StringBuilder();
        try {
            String provider = "sh";
            if (su) {
                provider = "/system/xbin/su";
                final File SU = new File(provider);
                if (SU != null && SU.exists()) {

                } else {
                    provider = "su";
                }
            }

            mProcess = Runtime.getRuntime().exec(provider);
            os = new DataOutputStream(mProcess.getOutputStream());
            es = new DataInputStream(mProcess.getErrorStream());
            is = new DataInputStream(mProcess.getInputStream());
            for (final String cmd : command) {
                sb.append((su ? "#sudo > " : "$sh > ") + cmd + "\n");
                os.writeBytes(cmd + "\n");
                os.flush();
                if (is != null) {
                    try {
                        byte[] buffer = new byte[is.available()];
                        int size = is.read(buffer);
                        if (size > 0) {
                            sb.append("\n" + new String(buffer));
                        }
                    } catch (Exception e) {

                    }
                }
                if (es != null) {
                    try {
                        byte[] buffer = new byte[es.available()];
                        int size = es.read(buffer);
                        if (size > 0) {
                            sb.append("\n" + new String(buffer));
                        }
                    } catch (Exception e) {

                    }
                }
            }
            os.writeBytes("exit\n");
            os.flush();
            mProcess.waitFor();
            Logger.debug(sb.toString());
        } catch (final Exception e) {
            Logger.debug(e);
            return false;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {

                }
            }
            if (es != null) {
                try {
                    es.close();
                } catch (IOException e) {

                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {

                }
            }
            if (mProcess != null)
                mProcess.destroy();
        }
        return true;
    }

}
